package com.itheima.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author zhangyan
 * @date 2021/3/16 10:54
 *
 * 全局过滤
 */

//@Component
public class CompanyFilter implements GlobalFilter, Ordered {

    //过滤器业务逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取请求与响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求参数值
        String params = request.getQueryParams().getFirst("dog");

        //判断
        if (!"wangwang".equals(params)) {

            //拒绝访问,返回错误代码
            response.setStatusCode(HttpStatus.BAD_REQUEST);
            return response.setComplete();
        }
        //放行
        return chain.filter(exchange);
    }

    //过滤器执行顺序,返回值int越小 优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
